
package com.huaweicloud.haydn.delivercore.agent.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessErrorEnum;
import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessException;

import static com.huaweicloud.haydn.delivercore.agent.config.Constants.SYS_URL;

/**
 * 功能描述
 *
 * @since 2022-12-21
 */
@Slf4j
public class HiveAuthUtil {

    public static void auth(String kr5bPath) {
        log.info("start to set hive auth jdbc info");
        System.setProperty("java.security.krb5.conf", kr5bPath);
        String zookeeper_default_server_principal = "zookeeper/" + getUserRealm();
        String zookeeper_server_principal_key = "zookeeper.server.principal";
        System.setProperty(zookeeper_server_principal_key, zookeeper_default_server_principal);

    }

    private static String getUserRealm() {
        String serverRealm = System.getProperty("SERVER_REALM");
        String auth_host_name;
        if (StringUtils.isNotBlank(serverRealm)) {
            auth_host_name = "hadoop." + serverRealm.toLowerCase(Locale.ENGLISH);
        } else {
            serverRealm = KerberosUtil.getKrb5DomainRealm();
            if (StringUtils.isNotBlank(serverRealm)) {
                auth_host_name = "hadoop." + serverRealm.toLowerCase(Locale.ENGLISH);
            } else {
                auth_host_name = "hadoop";
            }
        }
        return auth_host_name;
    }

    @SneakyThrows
    public static String getHiveAuthJDBC(String dbUserName, String dbDatabaseName) {
        Properties clientInfo = null;
        InputStream fileInputStream = null;
        try {
            clientInfo = new Properties();
            File propertiesFile = new File(System.getProperty(SYS_URL) + File.separator + "hiveclient.properties");
            fileInputStream = new FileInputStream(propertiesFile);
            clientInfo.load(fileInputStream);
        } catch (IOException e) {
            log.error("get hive auth failed!", e);
            throw new BusinessException(BusinessErrorEnum.BASE_INTERNAL_SERVER_ERROR, "get hive auth failed!");
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
        return dbDatabaseName + ";principal=" + clientInfo.getProperty("principal") + ";user.principal=" + dbUserName
                + ";user.keytab=" + System.getProperty(SYS_URL) + File.separator + "user.keytab;";
    }
}
